//
//  BCMRegistrationViewController.m
//  BCManagerVersion
//
//  Created by 吴 崧 on 14-2-22.
//  Copyright (c) 2014年 Jungle. All rights reserved.
//

#import "BCRegistrationViewController.h"
#import "UIAlertView+Blocks.h"
#import "BCLoginViewController.h"
#import "AFNetworking.h"
#import "UIImageView+AFNetworking.h"
#import "protocolViewController.h"
@interface BCRegistrationViewController () <UITextFieldDelegate>
@property (nonatomic, strong) NSString *securityId;
@end

@implementation BCRegistrationViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
	{
		self.securityId = nil;
		self.confirmProtocol = NO;
		// Custom initialization
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];
	[self loadSecuryCode];
	[self addFunctionToEndEdit];

	// Do any additional setup after loading the view from its nib.
}


- (IBAction)doRegister:(UIButton *)sender {
	if (self.confirmProtocol) {
		[UIAlertView showWithTitle:nil
		                   message:@"请确认用户使用协议"
		         cancelButtonTitle:@"确认"
		         otherButtonTitles:nil
		                  tapBlock: ^(UIAlertView *alertView, NSInteger buttonIndex) {
                          }];
	}
	else {
		__weak typeof(self) weakSelf = self;
        
		[BCProgressHUD showWithTile:@"注册中" animated:YES];
		[BCNetworkClient registerWithPassport:self.accountTF.text
		                             password:self.passwordTF.text
		                                 type:ClientType
		                             username:self.nameTF.text
		                                email:self.emailTF.text
		                           securityId:self.securityId
		                         securityCode:self.securityTF.text
		                              success: ^(int uid, NSString *auth) {
                                          USER_MANAGER.uid = @(uid);
                                          USER_MANAGER.auth = auth;
                                          
                                          NSString *devStr = [[NSUserDefaults standardUserDefaults] valueForKey:BCDeviceTokenKey];
                                          if (devStr.length > 0) {
                                              [BCNetworkClient bindPhoneId:devStr
                                                                      auth:USER_MANAGER.auth
                                                                   success:^{
                                                                       
                                                                   } failure:^(NSError *error) {
                                                                       
                                                                   }];
                                          }
                                          
                                          __weak UIViewController *vc = [self.navigationController.viewControllers firstObject];
                                          if ([vc isKindOfClass:[BCLoginViewController class]]) {
                                              if (((BCLoginViewController *)vc).complete) {
                                                  ((BCLoginViewController *)vc).complete(YES);
                                                  ((BCLoginViewController *)vc).complete = nil;
                                              }
                                              [weakSelf dismissViewControllerAnimated:YES completion: ^{
                                              }];
                                          }
                                      } failure: ^(NSError *error) {
                                          [BCProgressHUD hideWithError:error animated:YES];
                                          weakSelf.securityId = nil;
                                          [weakSelf loadSecuryCode];
                                      }];
	}
}

- (BOOL)validate {
	return [self validateAccount];
}

- (BOOL)validateAccount {
	return self.accountTF.text.length > 0 ? [self ValidateEmail] : NO;
}

- (BOOL)ValidateEmail {
	NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
	NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@", emailRegex];
	return [emailTest evaluateWithObject:self.emailTF.text] ? [self validatePassport] : NO;
}

- (BOOL)validatePassport {
	return self.nameTF.text.length > 0 ? [self validatePassword] : NO;
}

- (BOOL)validatePassword {
	return self.passwordTF.text.length > 0 ? [self validateProtocolConfirmed] : NO;
}

- (BOOL)validateProtocolConfirmed {
	return self.confirmProtocol ? [self validateSecurityInputed] : NO;
}

- (BOOL)validateSecurityInputed {
	return self.securityTF.text.length > 0 ? YES : NO;
}

- (IBAction)back:(id)sender {
	[self.view endEditing:YES];
	[self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)reloadSecuryCode {
	[self loadSecuryCode];
}

- (void)loadSecuryCode {
	__weak typeof(self) weakSelf = self;

	[BCNetworkClient securityCodeSuccess: ^(NSString *securityId, NSString *securityImageUrl) {
	    weakSelf.securityId = securityId;
	    NSLog(@"%@", securityImageUrl);
	    [weakSelf.securityImage setImageWithURL:[NSURL URLWithString:securityImageUrl]];
	} failure: ^(NSError *error) {
	    NSLog(@"error = %@", error);
	}];
}

- (IBAction)protocolBtnPressed:(UIButton *)sender {
	protocolViewController *protocol = [[protocolViewController alloc]init];
	__weak typeof(self) weakSelf = self;

	[protocol setCompeletion: ^(BOOL protocol) {
	    weakSelf.confirmProtocol = protocol;
	    NSString *titleString = protocol ? @"同意并阅读《客户协议》" : @"阅读《客户协议》";
	    NSString *imageName = protocol ? @"agree" : @"Disagree";
	    [weakSelf.protocolBtn setTitle:titleString forState:UIControlStateNormal];
	    [weakSelf.confirmImage setImage:[UIImage imageNamed:imageName]];
	}];
	[self.navigationController pushViewController:protocol animated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	if (textField.tag < 4) {
		[((UITextField *)[self.view viewWithTag:textField.tag + 1])becomeFirstResponder];
	}
	else if (textField.tag == 5) {
		[self.view endEditing:YES];
		[self doRegister:nil];
	}
	else {
		[self.view endEditing:YES];
	}
	return YES;
}

- (IBAction)didBeginSecurityInput:(UITextField *)sender {
	[UIView animateWithDuration:0.25 animations: ^{
	    self.view.frame = CGRectSetY(self.view.frame, -120);
	}];
}

- (IBAction)didFinishSecurityInput:(UITextField *)sender {
	[UIView animateWithDuration:0.25 animations: ^{
	    self.view.frame = CGRectSetY(self.view.frame, 0);
	}];
}

@end
